package com.ning.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.ning.api.IndexApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class IndexController {

    private final static String A_SERVICE_URL = "http://springcloud-service-a/";

    private static int count = 0;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private IndexApi indexApi;

    /**
     * 基于RestTemplate
     *
     * @param str
     * @return
     */
    @HystrixCommand(fallbackMethod = "defaultTimeout")
    @GetMapping(value = "/index")
    public Object index(String str) {
        System.out.println("Consumer IndexController index str => " + str);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("str", str);
        return restTemplate.postForObject(A_SERVICE_URL + "index", httpHeaders, String.class);
    }

    /**
     * 基于Feign消费服务
     *
     * @param str
     * @return
     */
    @GetMapping(value = "/feignIndex")
    public Object feignIndex(String str) {
        System.out.println("Consumer IndexController index2 str => " + str);
        String result = indexApi.index(str);
        System.out.println("Consumer IndexController index2 result => " + result);
        return result;
    }

    @GetMapping(value = "/timeout")
    public String timeout(String str) {
        return indexApi.timeout(str);
    }

    @HystrixCommand(fallbackMethod = "defaultTimeout")
    @GetMapping(value = "/count")
    public Object count(String str) {
        System.out.println("str => " + str);
        count++;
        return count;
    }

    public String defaultTimeout(String str) {
        return "timeout is business ! str => " + str;
    }

}
